String

The PowerShell string is simply an object with a System.String type.

A String can be defined in PowerShell by using the single or double-quotes.


Creating a basic string

Double-quoted strings

Strings are created by wrapping the text with double quotes. Double-quoted strings can evaluate variables and special characters.

$myString = "Some basic text" $variable = 007 $mySecondString = "String with a variable $variable"

To use a double quote inside a string it needs to be escaped using the escape character, backtick (`). Single quotes can be used inside a double-quoted string.

$myString = "A `"double quoted`" string which also has 'single quotes'."

Literal string

Literal strings are strings that doesn't evaluate variables and special characters. It's created using single quotes.

$myLiteralString = 'Simple text including special characters (`n) and a $variable-reference'

To use single quotes inside a literal string, use double single quotes or a literal here-string. Double quotes can be used safely inside a literal string

$myLiteralString = 'Simple string with ''single quotes'' and "double quotes".'

Here-string

Here-strings are very useful when creating multiline strings. One of the biggest benefits compared to other multiline strings are that you can use quotes without having to escape them using a backtick.

@" Simple Multiline string with "quotes" "@

You could also create a literal here-string by using single quotes, when you don't want any expressions to be expanded just like a normal literal string.

@' The following line won't be expanded $(Get-Date) because this is a literal here-string '@

Special characters

When used inside a double-quoted string, the escape character (backtick `) represents a special character

`0 #Null `a #Alert/Beep `b #Backspace `f #Form feed (used for printer output) `n #New line `r #Carriage return `t #Horizontal tab `v #Vertical tab (used for printer output) `# #Comment-operator `$ #Variable operator `` #Escape character `' #Single quote `" #Double quote > "This`tuses`ttab`nThis is on a second line" This uses tab This is on a second line

String Formatting

String formatting is a process to insert some characters or string inside a string. We can format the string by using the -f operator.

$s1="Windows PowerShell" $s2="POINT" $formattedString = "{0} {1}...." -f $s1,$s2 $formattedString

Concatenating strings

Using variables in a string

$string1 = "Power" $string2 = "Shell" "Greetings from $string1$string2"

Using the + operator

$string1 = "Greetings from" $string2 = "PowerShell" $string1 + " " + $string2 "The title of this console is '" + $host.Name + "'"

Using subexpressions

"Tomorrow is $((Get-Date).AddDays(1).DayOfWeek)"

String Replace

The replace() method accepts the two arguments and is used to replace the characters in a string.

$s1="Windows Powerxhell" $s1.replace("x","S")